package com.leapp.sk.ui.activity.login

import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.text.TextUtils
import android.view.View
import cc.vv.lkbasecomponent.http.LKHttp
import cc.vv.lkbasecomponent.http.lib.setting.Settings
import cc.vv.lklibrary.http.base.okhttpfactory.plugins.httpplugin.MediaTypeWrap
import com.example.baselibrary.util.LKToastUtil
import com.example.mvp.activity.BaseActivityMVP
import com.example.mvp.binder.BaseDataBinder
import com.example.util.ObjectProcessingUtil
import com.leapp.sk.R
import com.leapp.sk.app.GET_CODE
import com.leapp.sk.app.WX_BINDER_PHONE
import com.leapp.sk.bean.UserInfoEntity
import com.leapp.sk.bean.WXUserInfo
import com.leapp.sk.bean.request.login.MobileVerificationRequestEntity
import com.leapp.sk.bean.request.login.SendCodeRequestEntity
import com.leapp.sk.bean.response.login.LoginResponseEntity
import com.leapp.sk.bean.response.login.SendCodeResponseEntity
import com.leapp.sk.binder.BaseBinder
import com.example.im.IMInit
import com.leapp.sk.sever.login.UserInfoSever
import com.leapp.sk.ui.activity.AppMainTableActivity
import com.leapp.sk.ui.activity.join.SearchClassActivity
import com.leapp.sk.ui.activity.join.ToExamineActivity
import com.example.util.finallist.SKCODE_200
import com.example.util.finallist.WX_USER_INFO
import com.leapp.sk.viewdelegate.login.LoginMobileVerificationDelegate

/**
 * 微信登录手机号验证
 * @author  chaohaipeng  on 2018/8/22.
 */
class LoginMobileVerificationActivity : BaseActivityMVP<LoginMobileVerificationDelegate>(){
    /**
     * 计时器
     */
    private var timeCount: TimeCount? = null
    /**
     * 验证码
     */
    private var code: String?= ""
    /**
     * 微信数据
     */
    var obj: WXUserInfo?=null
    override fun bindEvenListener() {
        viewDelegate.setOnClickListener(View.OnClickListener {
            if (!TextUtils.isEmpty(viewDelegate?.verificationCodeCheck())) {
                timeCount?.start()
                httpCode(viewDelegate?.verificationCodeCheck())
            }
        }, R.id.tv_awmv_get_code)
        viewDelegate.setOnClickListener(View.OnClickListener {
            viewDelegate.clearContent()
        }, R.id.iv_awmv_clear_content)

        viewDelegate.setOnClickListener(View.OnClickListener {
            if (!TextUtils.isEmpty(viewDelegate.verificationCodeCheck()) && !TextUtils.isEmpty(viewDelegate.loginCheck())) {
                httpLogin(viewDelegate.verificationCodeCheck(), viewDelegate.loginCheck())
            }
        }, R.id.tv_awmv_next)
    }

    override fun initView(p0: Bundle?) {
        viewDelegate.setTitle(resources.getString(R.string.string_check_mobile_title))
        viewDelegate.setClearDatavisible()
    }

    override fun initDate() {
        obj= intent?.getSerializableExtra(WX_USER_INFO) as WXUserInfo?
        //构造CountDownTimer对象
        timeCount = TimeCount(60000, 1000)
    }


    override fun getDelegateClass(): Class<LoginMobileVerificationDelegate> {
        return LoginMobileVerificationDelegate::class.java
    }

    override fun getDataBinder(): BaseDataBinder<*, *> {

        return BaseBinder()
    }

    /**
     * 验证码倒计时
     */
    internal inner class TimeCount(millisInFuture: Long, countDownInterval: Long)//参数依次为总时长,和计时的时间间隔
        : CountDownTimer(millisInFuture, countDownInterval) {
        override fun onFinish() {
            //计时完毕时触发
            viewDelegate?.verificationCode(0)
        }

        override fun onTick(millisUntilFinished: Long) {
            // 计时过程显示
            viewDelegate?.verificationCode(millisUntilFinished)
        }
    }
    /**
     * 获取验证码
     */
    private fun httpCode(phone: String?) {
        if(phone==null){
            return
        }
        val sendCodeRequest = SendCodeRequestEntity()
        sendCodeRequest.phone = phone
        sendCodeRequest.type=4
        LKHttp.post(GET_CODE, sendCodeRequest, SendCodeResponseEntity::class.java, object : BaseCallBack<SendCodeResponseEntity>(this) {
            override fun onSuccess(url: String?, resultText: String?, obj: SendCodeResponseEntity?) {
                super.onSuccess(url, resultText, obj)
                if (obj?.code == SKCODE_200) {
                    val data = obj.data
                    code=data
                    viewDelegate?.setverificationCode(data)
                }else{
                    LKToastUtil.showToastShort(obj?.message)
                }
            }
            override fun onFailure(url: String?, isLoading: Boolean, exceptionStr: String?) {
                super.onFailure(url, isLoading, exceptionStr)
                LKToastUtil.showToastShort(resources.getString(R.string.app_net_erro))
            }
        }
                , true, Settings(MediaTypeWrap.MEDIA_TYPE_FORM))
    }

    /**
     * 登录
     */
    private fun httpLogin(phone: String, smCode: String?) {
        if (smCode==null){
            return
        }
        val loginRequestEntity = MobileVerificationRequestEntity()
        loginRequestEntity.phone = phone
        loginRequestEntity.smCode = smCode
        loginRequestEntity.avatar=obj?.headimgurl
        loginRequestEntity.nickName=obj?.nickname
        loginRequestEntity.openid=obj?.openid
        LKHttp.post(WX_BINDER_PHONE, loginRequestEntity, LoginResponseEntity::class.java, object : BaseCallBack<LoginResponseEntity>(this) {
            override fun onSuccess(url: String?, resultText: String?, obj: LoginResponseEntity?) {
                super.onSuccess(url, resultText, obj)
                if (obj?.code == SKCODE_200) {
                    IMInit.getInstance().login(phone)
                    UserInfoSever.getInstance().saveData(obj)
                    val userInfoEntity: UserInfoEntity = ObjectProcessingUtil.objMandatoryConversionClass(obj?.data, UserInfoEntity::class.java)
                    val name=userInfoEntity?.name
                    if (userInfoEntity.status==0){
                        if (TextUtils.isEmpty(name)){
                            val intent: Intent = Intent(this@LoginMobileVerificationActivity, PerfectUserInfoActivity::class.java)
                            startActivity(intent)
                        }else{
                            val intent: Intent = Intent(this@LoginMobileVerificationActivity, SearchClassActivity::class.java)
                            startActivity(intent)
                        }
                    }else if (userInfoEntity.status==1){
                        val intent: Intent = Intent(this@LoginMobileVerificationActivity, AppMainTableActivity::class.java)
                        startActivity(intent)
                    }else{
                        val intent: Intent = Intent(this@LoginMobileVerificationActivity, ToExamineActivity::class.java)
                        startActivity(intent)
                    }
                }else{
                    LKToastUtil.showToastShort(obj?.message)
                }
            }
            override fun onFailure(url: String?, isLoading: Boolean, exceptionStr: String?) {
                super.onFailure(url, isLoading, exceptionStr)
                LKToastUtil.showToastShort(resources.getString(R.string.app_net_erro))
            }
        }
                , true, Settings(MediaTypeWrap.MEDIA_TYPE_FORM))

    }





}